package com.financial.service.platbalancepay.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.financial.service.platbalancepay.service.BalancePayService;
import com.financial.service.platbalancepay.service.OperBalanceService;
import com.financial.service.platbalancepay.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * MQ消息处理类
 */


@Component
public class BalancePayMessageListener implements MessageListener {



    public static final Logger logger = LoggerFactory.getLogger(BalancePayMessageListener.class);
    @Autowired
    private OperBalanceService operBalanceService;
    @Autowired
    private BalancePayService balancePayService;
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
       /* logger.error(new Date() + "MessageListenerImpl Receive message, Topic is:" + message.getTopic()
                + ", MsgId is:" + message.getMsgID()+",tags is:"+message.getTag());

        return Action.CommitMessage;*/

        //Topic校验Tag校验
        if (!message.getTopic().equals(BalancePayMQConfig.BALANCEPAY_TOPIC) || StringUtils.isEmpty(message.getTag())) {
            logger.error("Topic不符合订阅要求，Topic：" + message.getTopic() + "或者Tag为空，Tag：" + message.getTag());
            return Action.CommitMessage;
        }
        //获取消息重试次数
        int reconsume = message.getReconsumeTimes();
        if (reconsume == 3) {
            logger.error("该消息重复消费三次，直接标识成功");
            return Action.CommitMessage;

        }
        //解析消息体
        Map<String, Object> result = JsonUtils.jsonToMap(new String(message.getBody()));
        /**
         * 通过TAG来判断处理方式
         *
         */
        logger.info("获取消息：" + result.toString());
        boolean handleResult = true;
        Map<String,Object> resultMap = null;
        //余额操作mq
        if (BalancePayMQConfig.BLANCEPAY.equals(message.getTag())) {
            logger.info("===========接收代付异步MQ============");
            resultMap = balancePayService.disposeBalanceasynPay(result);
        }
        if (!handleResult) {
            logger.error("处理失败；Tag：" + message.getTag());
        }
        return Action.CommitMessage;
    }


}
